<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommunityArticles, deleteArticle, createCommunityCategory, createCommunityArticle, getCommunityCategories, deleteCommunityCategory } from '@/api/community'
import { uploadFile } from '@/api/common'

const router = useRouter()

// 文章列表
const articles = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 分类弹窗相关
const showCategoryDialog = ref(false)
const categoryForm = ref({ name: '', description: '', sortOrder: 0 })
const categoryLoading = ref(false)

// 分类列表弹窗相关
const showCategoryListDialog = ref(false)
const categoryListLoading = ref(false)
const categoryDeleteLoading = ref({})

// 创建文章弹窗相关
const showCreateArticleDialog = ref(false)
const articleForm = ref({
  title: '',
  content: '',
  summary: '',
  coverImage: '',
  images: '',
  categoryId: '',
  status: 1 // 默认已发布
})
const articleLoading = ref(false)
const categories = ref([])

// 加载文章列表
const loadArticles = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
    }
    if (searchKeyword.value) {
      params.title = searchKeyword.value
    }
    const res = await getCommunityArticles(params)
    if ((res.code === 0 || res.code === 200) && res.data) {
      articles.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取文章失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadArticles()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  loadArticles()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadArticles()
}

// 删除文章
const handleDelete = (article) => {
  ElMessageBox.confirm(`确定要删除《${article.title}》吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  }).then(async () => {
    await deleteArticle(article.id)
    ElMessage.success('删除成功')
    loadArticles()
  }).catch(() => {})
}

// 查看文章详情
const handleView = (article) => {
  router.push(`/community/article/${article.id}`)
}

// 创建文章
const handleCreate = () => {
  showCreateArticleDialog.value = true
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCommunityCategories()
    if ((res.code === 0 || res.code === 200) && res.data) {
      categories.value = res.data || []
    }
  } catch (e) {
    console.error('获取分类列表失败:', e)
  }
}

// 显示分类列表弹窗
const handleShowCategoryList = async () => {
  showCategoryListDialog.value = true
  categoryListLoading.value = true
  
  try {
    await loadCategories()
  } finally {
    categoryListLoading.value = false
  }
}

// 删除分类
const handleDeleteCategory = async (category) => {
  ElMessageBox.confirm(`确定要删除分类"${category.name}"吗？删除分类可能会影响已关联该分类的文章。`, '警告', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonClass: 'el-button--danger'
  }).then(async () => {
    categoryDeleteLoading.value[category.id] = true
    try {
      const res = await deleteCommunityCategory(category.id)
      if ((res.code === 0 || res.code === 200) && res.data) {
        ElMessage.success('分类删除成功')
        // 重新加载分类列表
        await loadCategories()
      } else {
        ElMessage.error(res.message || '删除分类失败')
      }
    } catch (e) {
      console.error('删除分类失败:', e)
      ElMessage.error('删除分类失败')
    } finally {
      categoryDeleteLoading.value[category.id] = false
    }
  }).catch(() => {})
}

// 上传图片
const handleCoverUpload = async (file) => {
  try {
    const res = await uploadFile(file)
    if ((res.code === 0 || res.code === 200) && res.data) {
      articleForm.value.coverImage = res.data.url || res.data // 兼容不同后端返回
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (e) {
    ElMessage.error('图片上传失败')
  }
}

// 提交创建文章
const handleArticleSubmit = async () => {
  // 表单验证
  if (!articleForm.value.title.trim()) {
    ElMessage.warning('请输入文章标题')
    return
  }
  if (!articleForm.value.content.trim()) {
    ElMessage.warning('请输入文章内容')
    return
  }
  if (!articleForm.value.categoryId) {
    ElMessage.warning('请选择文章分类')
    return
  }

  articleLoading.value = true
  try {
    const res = await createCommunityArticle(articleForm.value)
    if ((res.code === 0 || res.code === 200) && res.data) {
      ElMessage.success('文章发布成功')
      showCreateArticleDialog.value = false
      // 重置表单
      articleForm.value = {
        title: '',
        content: '',
        summary: '',
        coverImage: '',
        images: '',
        categoryId: '',
        status: 1
      }
      // 刷新文章列表
      loadArticles()
    } else {
      ElMessage.error(res.message || '文章发布失败')
    }
  } catch (e) {
    console.error('发布文章失败:', e)
    ElMessage.error('文章发布失败')
  } finally {
    articleLoading.value = false
  }
}

const handleAddCategory = () => {
  categoryForm.value = { name: '', description: '', sortOrder: 0 }
  showCategoryDialog.value = true
}
const handleCategorySubmit = async () => {
  if (!categoryForm.value.name) {
    ElMessage.error('分类名称不能为空')
    return
  }
  categoryLoading.value = true
  try {
    const res = await createCommunityCategory(categoryForm.value)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('分类添加成功')
      showCategoryDialog.value = false
      // 重新加载分类列表
      loadCategories()
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } finally {
    categoryLoading.value = false
  }
}

onMounted(() => {
  loadArticles()
  loadCategories()
})
</script>

<template>
  <div class="community-manage-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索文章标题"
        class="search-input"
        @keyup.enter="handleSearch"
        clearable
        style="width: 300px;"
      />
      <el-button type="primary" @click="handleSearch" style="margin-left: 12px;">搜索</el-button>
      <el-button type="success" @click="handleCreate" style="margin-left: auto;">创建文章</el-button>
    </div>

    <!-- 文章列表 -->
    <el-card class="article-list">
      <el-table :data="articles" v-loading="loading" style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="220">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="作者" width="120" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="likeCount" label="点赞" width="80" />
        <el-table-column prop="collectCount" label="收藏" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="showCategoryDialog" title="添加文章分类" width="400px">
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称" required>
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="categoryForm.description" placeholder="可选，分类描述" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="categoryForm.sortOrder" :min="0" :max="9999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCategoryDialog = false">取消</el-button>
        <el-button type="primary" :loading="categoryLoading" @click="handleCategorySubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分类列表弹窗 -->
    <el-dialog v-model="showCategoryListDialog" title="删除文章分类" width="500px">
      <div v-loading="categoryListLoading">
        <div v-if="categories.length === 0" class="empty-categories">
          <el-empty description="暂无分类数据" />
        </div>
        <el-table v-else :data="categories" style="width: 100%">
          <el-table-column prop="name" label="分类名称" />
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="sortOrder" label="排序" width="80" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button 
                type="danger" 
                link 
                @click="handleDeleteCategory(row)"
                :loading="categoryDeleteLoading[row.id]"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showCategoryListDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 创建文章弹窗 -->
    <el-dialog v-model="showCreateArticleDialog" title="发布新文章" width="650px">
      <el-form :model="articleForm" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input 
            type="textarea" 
            v-model="articleForm.content" 
            placeholder="请输入文章内容" 
            rows="8"
            resize="none"
          />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input 
            type="textarea" 
            v-model="articleForm.summary" 
            placeholder="请输入文章摘要，不填则自动提取内容前200字" 
            rows="3"
          />
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="cover-uploader"
            action=""
            :http-request="({ file }) => handleCoverUpload(file)"
            :show-file-list="false"
          >
            <div v-if="articleForm.coverImage" class="image-preview">
              <img :src="articleForm.coverImage" class="preview-image" />
            </div>
            <el-button v-else type="primary">上传封面图</el-button>
          </el-upload>
          <div v-if="articleForm.coverImage" style="margin-top: 10px;">
            <el-button size="small" type="danger" @click="articleForm.coverImage = ''">
              移除图片
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="articleForm.categoryId" placeholder="请选择文章分类">
            <el-option 
              v-for="cat in categories" 
              :key="cat.id" 
              :label="cat.name" 
              :value="cat.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateArticleDialog = false">取消</el-button>
        <el-button type="primary" :loading="articleLoading" @click="handleArticleSubmit">发布文章</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.community-manage-container {
  padding: 32px 32px 32px 32px;
  background: linear-gradient(180deg, #f8fbff 0%, #f5f7fa 100%);
  min-height: 100vh;
}
.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 28px;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.06);
  padding: 18px 24px;
  gap: 18px;
}
.search-input {
  width: 300px;
  border-radius: 20px;
  overflow: hidden;
}
.article-list {
  margin-bottom: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.08);
  background: #fff;
  padding: 0 0 10px 0;
}
.el-table {
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
}
.el-table th, .el-table td {
  font-size: 15px;
  color: #333;
  background: #f8fbff;
}
.el-table th {
  font-weight: 700;
  background: #f0f7ff;
}
.el-table tr {
  transition: background 0.2s;
}
.el-table tr:hover {
  background: #f5faff;
}
.el-button[type="primary"], .el-button--primary {
  background: linear-gradient(90deg, #409eff 60%, #66b1ff 100%);
  border: none;
  color: #fff;
  border-radius: 20px;
  font-weight: 500;
  transition: box-shadow 0.2s;
}
.el-button[type="primary"]:hover, .el-button--primary:hover {
  box-shadow: 0 2px 8px rgba(64,158,255,0.15);
}
.el-button[type="success"], .el-button--success {
  border-radius: 20px;
  font-weight: 500;
}
.el-button[type="danger"], .el-button--danger {
  border-radius: 20px;
  font-weight: 500;
}
.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
.cover-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
}
.image-preview {
  width: 200px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.empty-categories {
  padding: 30px 0;
}
</style>